<template>
    <div class="sys-search">
        <el-form :model="searchForm" :label-position="$store.labelPosition" label-width="20%">
            <el-col :xs="23" :sm="14">
                <el-form-item label="订单号：" >
                    <el-input v-model="searchForm.orderNo" placeholder="请输入订单号"></el-input>
                </el-form-item>

                <el-form-item label="客户：">
                    <el-select v-model="searchForm.custId" clearable filterable
                               placeholder="请选择客户" style="width: 100%;">
                        <el-option v-for="cust in customers" :key="cust.id"
                                   :label="cust.name" :value="cust.id"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="时间范围：">
                    <el-col :span="11">
                        <el-date-picker type="date" placeholder="开始日期" v-model="searchForm.fromDate"
                                        value-format="yyyy-MM-dd" format="yyyy-MM-dd"
                                        clearable style="width: 100%;"></el-date-picker>
                    </el-col>
                    <el-col class="centerText" :span="2">-</el-col>
                    <el-col :span="11">
                        <el-date-picker type="date" placeholder="结束时间" v-model="searchForm.toDate"
                                        value-format="yyyy-MM-dd" format="yyyy-MM-dd" clearable style="width: 100%;"></el-date-picker>
                    </el-col>
                </el-form-item>

                <el-form-item label="订单状态：" >
                    <el-select v-model="searchForm.status" clearable placeholder="请选择" style="width: 100%;">
                        <el-option v-for="st in statusList" :key="st.code"
                                   :label="st.description" :value="st.code">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="searchOrdersByCriteria()">查询</el-button>
                    <el-button type="edit" icon="el-icon-plus" @click="gotoAddOrder()">添加</el-button>
                    <el-button type="danger" icon="el-icon-delete" @click="deleteOrders()">删除</el-button>

                </el-form-item>
            </el-col>
        </el-form>

        <table-mixin pagination paginationAlign="left" :paginationTotal="paginationTotal"
                     :pageChange="pageChange">
        <el-table v-loading="tableData.loading" :data="tableData.body"
                  @selection-change="handleSelectionChange" stripe border style="width:100%">
            <el-table-column type="selection"  align="center" width="30"
                :selectable="canSelectOrder"></el-table-column>

            <el-table-column label="订单号" prop="orderNo" min-width="10%"></el-table-column>
            <el-table-column label="客户" prop="custName" min-width="28%" ></el-table-column>
            <el-table-column label="接单日期" prop="orderDtStr" min-width="10%"></el-table-column>
            <el-table-column label="付款日期" prop="payDtStr" min-width="10%"></el-table-column>
            <el-table-column label="总金额" prop="totalAmountStr" min-width="10%"
                             align="right" header-align="center"></el-table-column>
            <el-table-column label="要求出货日期" prop="requireOutDtStr" min-width="10%"></el-table-column>
            <el-table-column label="订单状态"  min-width="8%" >
                <template slot-scope="scope">
                    <el-tag type="danger" v-if="scope.row.status == 0">{{scope.row.statusDescr}}</el-tag>
                    <el-tag type="warning" v-if="scope.row.status == 1">{{scope.row.statusDescr}}</el-tag>
                    <el-tag type="success" v-if="scope.row.status == 2">{{scope.row.statusDescr}}</el-tag>
                </template>
            </el-table-column>

            <el-table-column label="操作" class-name="centerCell" min-width="24%">
                <template slot-scope="scope">
                    <el-button type="edit" size="small" icon="el-icon-edit" v-if="!scope.row.closeFlag"
                        @click="gotoEditOrder(scope.row.id)">编辑</el-button>
                    <el-button type="edit" size="small" icon="el-icon-edit"
                               @click="copyOrder(scope.row.id)">复制</el-button>
                    <el-button type="edit" size="small" icon="el-icon-edit" v-if="canCloseOrder && !scope.row.closeFlag"
                               @click="closeOrder(scope.row.id)">关闭</el-button>
                    <el-button type="primary" size="small" icon="el-icon-view"
                        @click="gotoViewOrder(scope.row.id)">查看</el-button>
                </template>
            </el-table-column>
        </el-table>
        </table-mixin>

    </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
    name: "OrderSearch",
    data() {
        return {
            searchForm: {
                orderNo: '',
                fromDate: '',
                toDate: '',
                custId: '',
                status: ''
            },

            tableData: {
                loading: true,
                body: []
            },
            currentPage: 1,
            paginationTotal: 0,
            selectedOrders: []
        }
    },

    mounted() {
        this.searchOrdersByCriteria()
    },

    methods: {
        searchOrdersByCriteria(){
            this.currentPage = 1;
            this.searchOrder();
        },

        // 获取table数据
        async searchOrder() {
            console.log("this.currentPage: ", this.currentPage);
            let params = {
                pageSize: this.$store.state.pageSize,
                pageNo: this.currentPage};
            Object.assign(params,this.searchForm);
            let res = await this.$axios.get('/sell/order/list', params);

            console.log("返回订单列表：", res);
            this.tableData.loading = false;
            this.tableData.body = res.rows;
            this.paginationTotal = res.total;
        },

        pageChange(currentPage) {
            console.log(`当前第${currentPage}页`)
            this.currentPage = currentPage;
            this.searchOrder();
        },

        gotoAddOrder(){
            this.$store.dispatch('order/showEditOrder', -1)
        },

        gotoEditOrder(orderId) {
            this.$store.dispatch('order/showEditOrder', orderId)
        },

        async closeOrder(orderId){
            await this.$axios.put(`/sell/order/close/${orderId}`);
            this.searchOrdersByCriteria();
        },

        async copyOrder(orderId){
            let res = await this.$axios.put(`/sell/order/copy/${orderId}`);
            this.gotoEditOrder(res.result);
        },

        gotoViewOrder(orderId) {
            this.$store.dispatch('order/showViewOrder', orderId)
        },

        handleSelectionChange(val) {
            console.log("选中的元素: ", val); // val 中是所有选中的元素的值
            this.selectedOrders = val
        },

        canSelectOrder(row, index){
            return !row.closeFlag
        },

        deleteOrders(){
            if(this.selectedOrders.length === 0){
                this.$myMsg.warning("请选择要删除的订单")
                return;
            }

            this.$confirm('确实要删除选中的订单吗？', '确认信息', {
                distinguishCancelAndClose: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            })
            .then(() => {
                this.actualDeleteOrders();
            })
            .catch(action => {
                this.$myMsg.info('已放弃删除选中的订单。');
            });
        },

        async actualDeleteOrders(){
            let orderIds = [];
            for(let tmpOrder of this.selectedOrders){
                orderIds.push(tmpOrder.id)
            }

            await this.$axios.delete('/sell/order', orderIds);
            this.$myMsg.success('删除成功');
            orderIds = [];
            this.searchOrdersByCriteria();
            this.selectedOrders=[]
        },

        showCloseOrderBtn(order){
            if(this.canCloseOrder){
                return !order.closeFlag
            }else{
                return false;
            }
        }
    },

    computed: {
        ...mapState({
            customers: state => state.order.initPageData.customers,
            sells: state => state.order.initPageData.sells,
            receiptCompanies: state => state.order.initPageData.receiptCompanies,
            statusList: state => state.order.initPageData.statusList,
            canCloseOrder: state => state.order.initPageData.canCloseOrder,
        }),
    }
}
</script>

